<template>
  <div :class="inputflag ? 'art-cmt-container-1' : 'art-cmt-container-2'">
    <!-- 评论列表 -->
    <div class="cmt-list" v-if="commentlist.length > 0">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="false"
        offset="30"
        @load="onLoad"
      >
        <!-- 评论的 Item 项 -->
        <div class="cmt-item" v-for="(obj, index) in commentlist" :key="index">
          <!-- 头部区域 -->
          <div class="cmt-header">
            <!-- 头部左侧 -->
            <div class="cmt-header-left">
              <img :src="obj.aut_photo" alt="" class="avatar" />
              <span class="uname">{{ obj.aut_name }}</span>
            </div>
            <!-- 头部右侧 -->
            <div class="cmt-header-right">
              <van-icon
                name="good-job"
                size="0.426667rem"
                color="red"
                v-if="obj.is_liking"
                @click="likeFn(false, obj.com_id)"
              />

              <van-icon
                name="good-job-o"
                size="0.426667rem"
                color="gray"
                v-else
                @click="likeFn(true, obj.com_id)"
              />
              <span class="commentDZcount">{{ obj.like_count }}</span>
            </div>
          </div>
          <!-- 主体区域 -->
          <div class="cmt-body">
            {{ obj.content }}
            <span class="reply" @click="replyFn(obj)"
              ><span v-if="obj.reply_count > 0">{{ obj.reply_count }}</span
              >回复<van-icon name="arrow" size="0.32rem"
            /></span>
          </div>
          <!-- 尾部区域 -->
          <div class="cmt-footer">{{ formatDate(obj.pubdate) }}</div>
          <!-- 评论回复页面 -->
          <van-popup
            v-model="show"
            position="bottom"
            :style="{ height: '100%' }"
            closeable
            get-container="body"
            ><replylist :cmtObj="cmtobj" @addreply="addreplyFn"></replylist
          ></van-popup>
        </div>
      </van-list>
    </div>
    <!-- 没有评论时 -->
    <div class="van-empty" v-else>
      <img src="@/assets/shafa.jpeg" alt="" />
    </div>
    <!-- 底部添加评论区域 - 1 -->
    <div class="add-cmt-box van-hairline--top" v-if="inputflag">
      <div class="ipt-cmt-div" @click="inputflag = false">发表评论</div>
      <div class="icon-box">
        <van-badge :content="totalcount" max="99">
          <van-icon name="comment-o" size="0.53333334rem" @click="go" />
        </van-badge>
        <van-icon
          name="star"
          size="0.53333334rem"
          color="#FFCC22"
          v-if="collected"
          @click="collectFn(false)"
        />
        <van-icon
          name="star-o"
          size="0.53333334rem"
          v-else
          @click="collectFn(true)"
        />
        <van-icon name="share-o" size="0.53333334rem" />
      </div>
    </div>
    <!-- 底部添加评论区域 - 2 -->
    <div class="cmt-box van-hairline--top" v-else>
      <textarea
        id="demo"
        placeholder="友善评论、理性发言、阳光心灵"
        @blur="blurFn"
        v-focus
        v-model.trim="addcommentObj.content"
      ></textarea>
      <van-button
        type="default"
        :disabled="addcommentObj.content === ''"
        @click="FBcomment"
        >发布</van-button
      >
    </div>
  </div>
</template>

<script>
import {
  getAllComment,
  addComment,
  LikeComment,
  UnLikeComment,
} from '@/api/comments/index.js'
import { timeAgo } from '@/utils/date.js'
import replylist from './replylist.vue'
export default {
  name: 'CommentList',
  props: {
    collected: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      commentObj: {
        type: 'a', // 评论类型, 只能是'a'或'c', 'a'代表对文章的评论列表, 'c'代表对评论的回复列表
        source: this.$route.query.articleId, // 文章id或评论id, 如果type为'a'这里传递文章id, 如果type为'c'这里传评论id
        offset: null, // 偏移量id(评论id), 值为评论id, 偏移量, 表示告诉后台从此id往后返回数据给前端, 做加载更多效果 axios发现值为null会自动忽略此参数
        limit: 10, // 获取评论数量, 不传, 默认后台返回10条
      },
      totalcount: 0, // 评论总数
      commentlist: [], // 文章评论列表
      inputflag: true, // 是否展示底部评论区域1 true展示 false展示底部评论区域2
      addcommentObj: {
        target: this.$route.query.articleId, // 评论的目标id id可以为文章id或评论的id
        content: '', // 发表评论的内容
        art_id: null, // 对评论回复需要此参数值, 代表所属文章id, 对文章评论无需此参数
      },
      loading: false, // 上拉加载更多数据的状态
      finished: false, // 上拉加载 是否加载完毕
      show: false, // 是否展示评论回复界面
      cmtobj: {}, // 要传给评论的回复界面的对象
    }
  },
  created() {
    this.getallcomment()
  },
  methods: {
    // 获取所有评论列表
    async getallcomment() {
      const { data: res } = await getAllComment(this.commentObj)
      if (res.message !== 'OK') {
        return this.$notify({ type: 'danger', message: '获取数据失败' })
      }
      console.log('该文章的评论列表数据:', res)
      this.loading = false
      if (res.data.results.length === 0) return (this.finished = true)
      this.commentlist = [...this.commentlist, ...res.data.results]
      this.totalcount = res.data.total_count
      this.commentlist.forEach((x) => (this.totalcount += x.reply_count))
      this.commentObj.offset = res.data.last_id // 偏移量 用来请求下一页数据
    },
    // 点赞/取消点赞 该评论
    async likeFn(flag, id) {
      const findResult = this.commentlist.find((x) => x.com_id === id)
      if (flag) {
        // 点击了点赞按钮 调用点赞评论接口 展示已点赞按钮 点赞数量加1
        const { data: res } = await LikeComment(id)
        if (res.message !== 'OK') {
          return this.$notify({ type: 'danger', message: '操作失败' })
        }
        findResult.is_liking = true
        findResult.like_count++
      } else {
        // 再次点击点赞按钮 调用取消点赞评论接口 展示点赞按钮点赞数量减1
        const { data: res } = await UnLikeComment(id)
        findResult.is_liking = false
        findResult.like_count--
        console.log(res)
      }
    },
    // 是否收藏该文章
    collectFn(flag) {
      this.$emit('collectFn', flag)
    },
    // 输入框失焦事件
    blurFn() {
      setTimeout(() => {
        this.inputflag = true
        this.addcommentObj.content = ''
      }, 0)
    },
    // 跳转到评论区的位置
    go() {
      document.querySelector('.like-box').scrollIntoView({ behavior: 'smooth' })
    },
    // 输入框内容输完--->发布文章评论
    // 发现bug-->当点击发布 输入框失焦 然后就隐藏了该输入框和发布按钮 也就没有了发布按钮的点击事件
    // 解决--->让输入框失焦事件延时触发
    async FBcomment() {
      delete this.addcommentObj.art_id
      const { data: res } = await addComment(this.addcommentObj)
      if (res.message !== 'OK') {
        return this.$notify({ type: 'danger', message: '操作失败' })
      }
      this.commentlist.unshift(res.data.new_obj)
      this.$toast({ type: 'success', message: '发布成功', duration: 500 })
      this.totalcount++
      this.go()
    },
    // 上拉加载更多
    onLoad() {
      if (this.commentlist.length > 0) {
        this.getallcomment()
      }
    },
    // 点击了回复按钮
    replyFn(obj) {
      this.cmtobj = obj
      this.show = true
    },
    // 一个评论的回复又新增一个
    addreplyFn(id) {
      const findResult = this.commentlist.find((x) => x.com_id === id)
      findResult.reply_count++
      this.totalcount++
    },
    // 格式化时间
    formatDate(str) {
      return timeAgo(str)
    },
  },
  components: {
    replylist,
  },
}
</script>

<style scoped lang="less">
.cmt-list {
  padding: 10px;
  .cmt-item {
    padding: 15px 0;
    + .cmt-item {
      border-top: 1px solid #f8f8f8;
    }
    .cmt-header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .cmt-header-left {
        display: flex;
        align-items: center;
        .avatar {
          width: 40px;
          height: 40px;
          background-color: #f8f8f8;
          border-radius: 50%;
          margin-right: 15px;
        }
        .uname {
          font-size: 12px;
        }
      }
    }
    .cmt-body {
      position: relative;
      font-size: 14px;
      line-height: 28px;
      text-indent: 4em;
      margin-top: 6px;
      word-break: break-all;
    }
    .cmt-footer {
      font-size: 12px;
      color: gray;
      margin-top: 10px;
      text-indent: 10em;
    }
  }
}
//点赞数量文字
.commentDZcount {
  color: gray;
  font-size: 16px;
  margin-left: 10px;
}
//回复
.reply {
  position: absolute;
  top: 34px;
  left: 50px;
  width: 60px;
  height: 25px;
  background: #f7f8fa;
  border-radius: 12px;
  display: inline-block;
  line-height: 25px;
  text-align: center;
  font-size: 12px;
  text-indent: 0;
}

/*美化 - 文章详情 - 底部的评论页面 */
// 外层容器
.art-cmt-container-1 {
  padding-bottom: 46px;
}
.art-cmt-container-2 {
  padding-bottom: 80px;
}

// 发布评论的盒子 - 1
.add-cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  box-sizing: border-box;
  background-color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 46px;
  line-height: 46px;
  padding-left: 10px;
  .ipt-cmt-div {
    flex: 1;
    border: 1px solid #efefef;
    border-radius: 15px;
    height: 30px;
    font-size: 12px;
    line-height: 30px;
    padding-left: 15px;
    background-color: #f8f8f8;
  }
  .icon-box {
    width: 40%;
    display: flex;
    justify-content: space-evenly;
    line-height: 0;
  }
}

.child {
  width: 20px;
  height: 20px;
  background: #f2f3f5;
}

// 发布评论的盒子 - 2
.cmt-box {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 80px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  padding-left: 10px;
  box-sizing: border-box;
  background-color: white;
  textarea {
    flex: 1;
    height: 66%;
    border: 1px solid #efefef;
    background-color: #f8f8f8;
    resize: none;
    border-radius: 6px;
    padding: 5px;
  }
  .van-button {
    height: 100%;
    border: none;
  }
}
/deep/ .van-badge {
  position: absolute !important;
  top: 0 !important;
  right: 0 !important;
}
</style>
